package manager.image;

import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Set;

import javax.media.opengl.GL;

import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.TextureIO;

public class TextureManager {

	/**
	 * Hashtable ID/Image of all the images which should be painted in the
	 * current screen (facing right)
	 */
	private Hashtable<String, Texture> textures = new Hashtable<String, Texture>();
	/**
	 * Singleton instance
	 */
	private static TextureManager instance;

	/**
	 * Singleton
	 * 
	 * @return the instance of the Singleton
	 */
	public static TextureManager getInstance() {
		if (instance == null)
			instance = new TextureManager();

		return instance;
	}

	/**
	 * Reset the buffer by loading images from a list of ID/Images path
	 * 
	 * @param toLoad
	 *            ID/Image path of all the images which should be painted in the
	 *            current screen
	 */
	public void reset(Hashtable<String, String> toLoad) {
		// Clear loaded images and collect the garbage
		textures.clear();
		System.gc();

		Set<String> keys = toLoad.keySet();
		Texture tex = null;

		for (String key : keys) {

			try {
				tex = TextureIO.newTexture( new File(key), false);
				tex.setTexParameteri(GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
				tex.setTexParameteri(GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);

			} catch (IOException e) {
				System.out.println("Failed to load texture : " + key);
				e.printStackTrace();
			}
			textures.put(key, tex);
		}
	}

	/**
	 * Get the image stored under the given name (ID)
	 * 
	 * @param name
	 *            The ID of the image to load
	 * @return the image stored under the given name (ID)
	 */
	public Texture getTexture(String name) {
		return textures.get(name);
	}
}
